/*
 * 创建日期 2009-9-13
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.common.util;

import  org.fantasy.common.eval.BaseCalculator;
import  org.fantasy.common.eval.Calculator;

import java.math.BigDecimal;

import org.apache.commons.beanutils.BasicDynaBean;
import org.apache.commons.beanutils.BasicDynaClass;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import bsh.Interpreter;

/**
 *  计算表达式工具
 * @author: 王文成
 * @version: 1.0
 * @since 2009-9-13
 */
public class ExpressionUtil {
    private static final Log log = LogFactory.getLog(ExpressionUtil.class);

    private ExpressionUtil() {

    }

    /**
     * 计算表达式值
     * 
     * @param expression
     * @param result
     */
    public static BigDecimal eval(String expression) throws Exception {
        try {
            Calculator cal = new BaseCalculator(expression);
            return cal.eval();
        } catch (Exception e) {
            log.info(e);
            return new BigDecimal(0);
        }
    }
    
    /**
     * 计算表达式值
     * 
     * @param expression
     * @param result
     */
    public static BigDecimal eval(Interpreter shell,String expression) throws Exception {
        Object result = shell.eval(getEvalExpression(expression));
        String value = result.toString();
        return getBigDecimal(value);
    }

    /**
     * 取得值
     * 
     * @param value
     * @return
     */
    private static BigDecimal getBigDecimal(String value) {
        try {
            return new BigDecimal(value);
        } catch (NumberFormatException e) {
            log.error(e + " value=[" + value + "]");
            return new BigDecimal(0);
        }
    }
    
    /**
     * 取得执行表达式
     * 
     * @param exp
     * @return
     */
    private static String getEvalExpression(String expression) {
        log.debug(expression);
        return expression;
    }

    public static void main(String[] args) throws Exception {
        DynaProperty prop1 = new DynaProperty("a", String.class);
        DynaProperty prop2 = new DynaProperty("b", String.class);
        DynaProperty prop3 = new DynaProperty("c", String.class);
        DynaClass dynaClass = new BasicDynaClass("", BasicDynaBean.class, new DynaProperty[] { prop1, prop2, prop3 });
        DynaBean bean = dynaClass.newInstance();
        bean.set("a", "100");
        bean.set("b", "200");
        bean.set("c", "300");
        //log.info(eval("(#a#/#b#/#c# - 100)*100", bean));
    }
}
